<?php
namespace app\examScore\controller;
use app\common\Base;
use app\examScore\model\ExamScoreModel;
use app\common\Excel;
use think\Db;
//--登分模板下载
class ExamScoreTemplate extends Base {
	
	public function index() {
		return $this->fetch();
	}

	public function pageQuery() {
		$examId = input("examId");
		$subject = input("subject");
		$fields = input("fields");
		$page = input("page");
		$rows = input("rows");
		if(!$examId) return [];
		$subWhere["考试ID"] = $examId;
		$subWhere["学科"] = $subject;
		$grade = getGradeByGradeId(Db::table("考试名称")->field("年级ID gradeId")->where("ID=".$examId)->find()["gradeId"]);
		$where["转出学期ID"] = 0;
		$where["年级号"] = $grade;
		$subsql = Db::table('各题得分'.$grade)
				  ->where($subWhere)
				  ->buildSql();
		$result = Db::table('学生信息')->alias('a')
					->join([$subsql=>'b'],'a.ID=b.学生ID','LEFT')
					->field("b.ID,a.班号,学号,a.ID 学生ID,姓名,'".$subject."' 学科,总分,".$fields)
					->where($where)
					->order("班号,学号")
					->page($page, $rows)
					->select();
		$count = Db::table("学生信息")->alias('a')
				  ->join([$subsql=>'b'],'a.ID=b.学生ID','LEFT')
				  ->where($where)
				  ->count();
		$grid["rows"] = selectResult($result);
		$grid["total"] = $count;
		return $grid;
	}

	public function addUpdate() {
		$param = request()->param();
		$where["考试ID"] = $param["考试ID"];
		$where["学生ID"] = $param["学生ID"];
		$where["学科"] = $param["学科"];
		$where["班号"] = $param["班号"];
		$grade = getGradeByGradeId(Db::table("考试名称")->field("年级ID gradeId")->where("ID=".$param["考试ID"])->find()["gradeId"]);
		$qv = Db::table('各题得分'.$grade)
			  ->field("ID")
			  ->where($where)
			  ->find();
		$examData = Db::table('考试名称')
				->field("考试科目 subject,满分数 fullScore")
				->where("ID=".$param["考试ID"])
				->find();
		$examSubject = explode(",", $examData['subject']);
		$subjectScore = explode(",", $examData['fullScore']);
		$fullScore = 0;
		foreach ($examSubject as $key => $value) {
			if($where["学科"] == $value) {
				$fullScore = floatval($subjectScore[$key]);
			}
		}
		$total = 0;
		foreach ($param as $key => $value) {
			if(strpos($key,"题型") !== false){
				$where[$key] = $value;
				$total += floatval($value);
			}
		}
		if($total > $fullScore) {
			$total = $fullScore;
		}
		$where["总分"] = $total;
		if($qv) {
			$where["ID"] = $qv["ID"];
			update('各题得分'.$grade, $where);
		}else {
			insert('各题得分'.$grade, $where);
		}
		return $total;
	}

	public function getScoreParam() {
		$examId = input("examId");
		$subject = input("subject");
		$Model = new ExamScoreModel();
		return $Model->getGetidefenParam($examId, $subject);
	}

	public function exportExcel() {
		$examId = input("examId");
		$examName = input("examName");
		$subject = input("subject");
		if(!$examId) return [];
		$Model = new ExamScoreModel();
		$params = $Model->getGetidefenParam($examId, $subject);
		$list = explode(",", $params);
		foreach ($list as $key => $value) {
			$fields[$key] = "题型".($key + 1);
			$exportParam[$key] = explode(":", $value)[0];
		}
		$fields = implode(",", $fields);
		$subWhere["考试ID"] = $examId;
		$subWhere["学科"] = $subject;
		$grade = getGradeByGradeId(Db::table("考试名称")->field("年级ID gradeId")->where("ID=".$examId)->find()["gradeId"]);
		$where["转出学期ID"] = 0;
		$where["转出学期ID"] = 0;
		$where["年级号"] = $grade;
		$subsql = Db::table('各题得分'.$grade)
				  ->where($subWhere)
				  ->buildSql();
		$result = Db::table('学生信息')->alias('a')
					->join([$subsql=>'b'],'a.ID=b.学生ID','LEFT')
					->field("b.ID,a.班号,学号,a.ID 学生ID,姓名,'".$subject."' 学科,总分,".$fields)
					->where($where)
					->order("班号,学号")
					->select();
		$fields = explode(",", "学生ID,班号,学号,姓名,".$fields);
		$paramlist = explode(",", "学生ID,班号,学号,姓名,".implode(",", $exportParam));
		$header = [];
		foreach ($paramlist as $key => $value){
			$header[$value] = $fields[$key];
		}
		$excelName = $examName."-".$subject."-登分模板";
		Excel::toExcel(selectResult($result),$excelName,$header);
		exit;
	}

	function importExcel() {
		$examId = input("examId");
		$subject = input("subject");
	    //上传excel文件
	    $file = request()->file('files');
	    $data = Excel::importExcel($file);
	    if(count($data) == 0) {
	    	return "没有数据！";
	    }
	    try {
	    	$where["考试ID"] = $examId;
	    	$where["学科"] = $subject;
	    	$grade = getGradeByGradeId(Db::table("考试名称")->field("年级ID gradeId")->where("ID=".$examId)->find()["gradeId"]);
			$Model = new ExamScoreModel();
			$params = $Model->getGetidefenParam($examId, $subject);
			$paramsList = explode(",", $params);
			$params = "考试ID,学生ID,班号,学科";
			foreach ($paramsList as $key => $value) {
				$fieldsList["题型".($key + 1)] = explode(":", $value)[0];
				$params = $params.",题型".($key + 1);
			}
			$paramsList = explode(",", $params);
	    	$addList=[];
	    	$updateList=[];
	    	$hadList = selectResult(Db::table('各题得分'.$grade)->where($where)->select());
	    	$ai = 0;
	    	$ui = 0;
	    	foreach ($data as $key => $obj) {
	    		$addM = [];
	    		$totalScore = 0;
	    		$obj["考试ID"] = $examId;
	    		$obj["学科"] = $subject;
	    		foreach ($paramsList as $key2 => $value2) {
	    			if(array_key_exists($value2, $fieldsList)) {
	    				$addM[$value2] = $obj[$fieldsList[$value2]];
	    				if($fieldsList[$value2] == '卷面分') {
							$totalScore -= floatval($addM[$value2]);
	    				}else {
	    					$totalScore += floatval($addM[$value2]);
	    				}
	    			}else {
	    				$addM[$value2] = $obj[$value2];
	    			}
	    		}
	    		$addM["总分"] = $totalScore;
	    		$isAdd = true;
	    		if(count($hadList) > 0) {
	    			foreach ($hadList as $hk => $hv) {
	    				if($hv["学生ID"] == $obj["学生ID"]) {
	    					$addM["ID"] = $hv["ID"];
	    					$updateList[$ui] = $addM;
	    					$ui += 1;
	    					$isAdd = false;
	    					break;
	    				}
	    			}
	    		}
	    		if($isAdd){
					$addList[$ai] = $addM;
	    			$ai += 1;
	    		}
	    	}
	    	if(count($addList) > 0) {
				Db::table('各题得分'.$grade)->insertAll($addList);
	    	}
	    	if(count($updateList) > 0) {
	    		foreach ($updateList as $key => $value) {
	    			update('各题得分'.$grade,$value);
	    		}
	    	}
	    } catch (\Exception $e) {
	    	return $e->getMessage();
	    }
	    return "000";
	}

	function getExamList() {
		return Db::table("考试名称")->alias("a")
				  ->join("年级名称 b","a.年级ID=b.ID","LEFT")
				  ->field("a.ID,a.年级ID gradeId,年级名称+考试名称 examName")
				  ->where("a.登分终止日期 > getDate()")
				  ->select();
		return $result;
	}

	function getSubject() {
		return Db::table("学科名称")
				->field("学科名称 gradeName")
				->where("ID<11")
				->select();    
	}

}
